import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'

import { BASE_URL, TIME_OUT } from '../config'
import type { ResponseDataType } from './type'
import storage from '@/storage'

const request: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
})
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    config.headers.Authorization = `Bearer ${storage.get('token')}`

    return config
  },
  (err: AxiosError) => {
    throw Promise.reject(err)
  },
)

request.interceptors.response.use(
  (response: AxiosResponse<ResponseDataType>): any => {
    if (response.status !== 200) {
      throw Promise.reject(response.statusText)
    }
    return response.data
  },
  (err: AxiosError) => {
    throw Promise.reject(err)
  },
)
export default request
